<template>
  <div>
    <Header/>
    <div class="login-container">
      <div class="login-box">
        <h2 class="login-title">账号登录</h2>

        <div class="login-tabs">
          <span :class="['tab-item', { active: loginType === 'password' }]"
                @click="loginType = 'password'">密码登录</span>
          <span :class="['tab-item', { active: loginType === 'sms' }]"
                @click="loginType = 'sms'">短信登录</span>
        </div>

        <div class="login-form">
          <!-- 手机号输入 -->
          <div class="form-item" v-if="loginType=='password'">
            <input type="text"
                   v-model="form.username"
                   placeholder="请输入用户名"
                   @blur="validateUsername">
            <span class="error-tip" v-if="errors.username">{{ errors.username }}</span>
          </div>

          <div class="form-item" v-if="loginType==='sms'" >
            <input type="text"
                   v-model="form.phone"
                   placeholder="请输入手机号"
                   @blur="validatephone">
            <span class="error-tip" v-if="errors.phone">{{ errors.phone }}</span>
          </div>

          <!-- 密码登录 -->
          <div class="form-item" v-if="loginType === 'password'">
            <input :type="showPassword ? 'text' : 'password'"
                   v-model="form.password"
                   placeholder="请输入密码">
            <span class="toggle-password" @click="showPassword = !showPassword">
              {{ showPassword ? '隐藏' : '显示' }}
            </span>
            <span class="error-tip" v-if="errors.password">{{ errors.password }}</span>
          </div>

          <!-- 短信验证码登录 -->
          <div class="form-item sms-code" v-if="loginType === 'sms'">
            <input type="text"
                   v-model="form.smsCode"
                   placeholder="请输入验证码">
            <button class="send-code-btn"
                    :disabled="countdown > 0"
                    @click="sendSmsCode">
              {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
            </button>
            <span class="error-tip" v-if="errors.smsCode">{{ errors.smsCode }}</span>
          </div>

          <!-- 记住密码选项 -->
          <div class="form-item remember-row">
            <label class="remember-pwd">
              <input type="checkbox" v-model="form.remember">
              <span>记住密码</span>
            </label>
            <a href="#" class="forget-pwd">忘记密码？</a>
          </div>

          <!-- 登录按钮 -->
          <button class="login-btn" @click="handleLogin">登录</button>

          <!-- 其他登录方式 -->
          <div class="other-login">
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="social-login">
              <a href="#" class="social-item wechat">
                <i class="iconfont icon-wechat"></i>
              </a>
              <a href="#" class="social-item qq">
                <i class="iconfont icon-qq"></i>
              </a>
            </div>
          </div>

          <!-- 注册入口 -->
          <div class="register-link">
            还没有账号？<a href="#" @click.prevent="goToRegister">立即注册</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'
import Header from '../components/Header.vue'

const router = useRouter()
const loginType = ref('password') // 登录方式：password/sms
const showPassword = ref(false)
const countdown = ref(0)

// 表单数据
const form = reactive({
  username: '',  // 修改为username
  password: '',
  smsCode: '',
  remember: false,
  phone:''
})

// 表单错误信息
const errors = reactive({
  username: '',  // 修改为username
  password: '',
  smsCode: '',
  phone:''
})
const validatephone=()=>{
  const phoneRegex=/^1[3-9]\d{9}$/
  if(!form.phone){
    errors.phone='请输入手机号'
  }else if(!phoneRegex.test(form.phone)){
    errors.phone='请输入正确的手机号'
  }else {
    errors.phone=""
    return true
  }
  return false

}
const sendSmsCode=()=>{
  if(!validatephone())return
  axios.post('http://127.0.0.1:8000/users/sms/code/',{
    'mobile':form.phone
  }).then(res=>{
    console.log(res)
    if (res.data.code==1){
      alert('验证码发送成功')
      countdown.value=60
      const  timer=setInterval(()=>{
        countdown.value--
        if(countdown.value<=0){
          clearInterval(timer)
        }
      },1000)
  }else{
    alert(res.data.message)
    }
  })
}

const validateUsername=()=>{
  if(!form.username){
    errors.username = '请输入用户名'

  }else {
    errors.username=''
  }
  return !errors.username
}
const handleLogin=()=>{
  if(loginType.value=='password'){
    if(!validateUsername())return
    if(!form.password){
      errors.password='请输入密码'
      return
    }
  }else {
    if(!validatephone())return
    if(!form.smsCode){
      errors.smsCode='请输入验证码'
      return
    }
  }
  if(loginType.value=='password') {
    try {
      axios.post('http://127.0.0.1:8000/users/login/', {
        username: form.username,
        password: form.password
      }).then(
          res => {
            console.log(res)
            if (res.data.code == 1) {
              alert('登陆成功')
              if (form.remember) {

                localStorage.setItem('token', res.data.data.token)
                localStorage.setItem('refresh_token', res.data.data.refresh)
                localStorage.setItem('username', res.data.data.username)
                localStorage.setItem('userId', res.data.data.userId)

              } else {
                sessionStorage.setItem('token', res.data.data.token)
                sessionStorage.setItem('refresh_token', res.data.data.refresh)
                sessionStorage.setItem('username', res.data.data.username)
                sessionStorage.setItem('userId', res.data.data.userId)

              }
              router.push('/')
            } else {
              alert('登录失败')
            }
          })
    } catch (err) {
      console.log(err)
      if (err.response && err.response.data) {
        const errorMsg = err.response.data.message || '登录失败'
        if (loginType.value == 'password') {
          errors.password = errorMsg
        }
      }
    }
  }else {
    try {
     axios.post('http://127.0.0.1:8000/users/mobile/',{
       'mobile':form.phone,
       'code':form.smsCode
      }).then(
          res=> {
            console.log(res)
            if(res.data.code==1){
            alert('登录成功')
            if (form.remember) {
              localStorage.setItem('token', res.data.data.token)
              localStorage.setItem('refresh_token', res.data.data.refresh)
              localStorage.setItem('username', res.data.data.username)
              localStorage.setItem('userId', res.data.data.userId)
            } else {
              sessionStorage.setItem('token', res.data.data.token)
              sessionStorage.setItem('refresh_token', res.data.data.refresh)
              sessionStorage.setItem('username', res.data.data.username)
              sessionStorage.setItem('userId', res.data.data.userId)
            }
            router.push('/')
          }else{
            alert(res.data.message)
      }
    })
    }catch(err){
    alert('登录失败')
  }
}
}
</script>

<style scoped>
.login-container {
  min-height: calc(100vh - 60px); /* 减去header的高度 */
  margin-top: 60px; /* header的高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.login-tabs {
  display: flex;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab-item.active {
  color: #ff6b00;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 40%;
  height: 2px;
  background: #ff6b00;
}

.form-item {
  margin-bottom: 20px;
  position: relative;
}

.form-item input {
  width: 100%;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-item input:focus {
  border-color: #ff6b00;
  outline: none;
}

.error-tip {
  position: absolute;
  left: 0;
  bottom: -20px;
  color: #f56c6c;
  font-size: 12px;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}

.sms-code {
  display: flex;
  gap: 10px;
}

.sms-code input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  padding: 0 15px;
  border: 1px solid #ff6b00;
  border-radius: 4px;
  background: white;
  color: #ff6b00;
  cursor: pointer;
  white-space: nowrap;
}

.send-code-btn:disabled {
  border-color: #dcdfe6;
  color: #909399;
  cursor: not-allowed;
}

.remember-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remember-pwd {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  cursor: pointer;
}

.forget-pwd {
  color: #909399;
  text-decoration: none;
}

.forget-pwd:hover {
  color: #ff6b00;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #ff6b00;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.login-btn:hover {
  background: #ff8533;
}

.other-login {
  margin-top: 24px;
}

.divider {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #dcdfe6;
  margin: 0 16px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.social-item {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
  transition: all 0.3s;
}

.social-item.wechat {
  background: #07c160;
}

.social-item.qq {
  background: #12b7f5;
}

.social-item:hover {
  transform: translateY(-2px);
}

.register-link {
  margin-top: 20px;
  text-align: center;
  color: #606266;
}

.register-link a {
  color: #ff6b00;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>